﻿using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace Business
{
    public static class FileConverter
    {
        /// <summary>
        /// 处理不同类型的文件，将其转换为制表符分隔的 TXT
        /// </summary>
        /// <param name="filePath">原始文件路径</param>
        /// <returns>转换后的 TXT 文件路径</returns>
        public static string ConvertToTxt(string filePath)
        {
            string extension = Path.GetExtension(filePath).ToLower();
            string txtFilePath = Path.ChangeExtension(filePath, ".txt");

            if (extension == ".csv")
            {
                ConvertCsvToTxt(filePath, txtFilePath);
            }
            else if (extension == ".xlsx")
            {
                ConvertExcelToTxt(filePath, txtFilePath);
            }
            else if (extension == ".txt")
            {
                return filePath; // 直接返回
            }
            else
            {
                throw new NotSupportedException("不支持的文件格式！");
            }

            return txtFilePath;
        }

        /// <summary>
        /// CSV 转 TXT（制表符分隔）
        /// </summary>
        private static void ConvertCsvToTxt(string csvFilePath, string txtFilePath)
        {
            using (StreamReader reader = new StreamReader(csvFilePath))
            using (StreamWriter writer = new StreamWriter(txtFilePath, false, Encoding.UTF8))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string tabSeparatedLine = line.Replace(",", "\t");
                    writer.WriteLine(tabSeparatedLine);
                }
            }
        }

        public static void ConvertExcelToTxt(string excelFilePath, string txtFilePath)
        {
            Application excelApp = new Application();
            Workbook workbook = excelApp.Workbooks.Open(excelFilePath);
            Worksheet worksheet = workbook.Sheets[1]; // 读取第一张表
            Range usedRange = worksheet.UsedRange;

            using (StreamWriter writer = new StreamWriter(txtFilePath, false, Encoding.UTF8))
            {
                for (int row = 1; row <= usedRange.Rows.Count; row++)
                {
                    List<string> rowData = new List<string>();
                    for (int col = 1; col <= usedRange.Columns.Count; col++)
                    {
                        object cellValue = usedRange.Cells[row, col].Value;
                        rowData.Add(cellValue?.ToString() ?? string.Empty);
                    }
                    writer.WriteLine(string.Join("\t", rowData));
                }
            }

            workbook.Close(false);
            excelApp.Quit();

            // 释放 COM 资源
            Marshal.ReleaseComObject(worksheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(excelApp);
        }
    }
}
